package com.example.com.transcribeeditpublish.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.example.com.transcribeeditpublish.BR;
import com.example.com.transcribeeditpublish.R;
import com.example.com.transcribeeditpublish.base.SignatureService;
import com.example.com.transcribeeditpublish.databinding.ActivityPreviewBinding;
import com.example.com.transcribeeditpublish.utils.RetrofitClient;
import com.example.com.transcribeeditpublish.utils.TCConstants;
import com.example.com.transcribeeditpublish.videoupload.TXUGCPublish;
import com.example.com.transcribeeditpublish.videoupload.TXUGCPublishTypeDef;
import com.example.com.transcribeeditpublish.views.VideoWorkProgressFragment;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayConfig;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.TXVodPlayConfig;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

import java.io.File;

import io.reactivex.Completable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.BaseUrlExternalStrageDir;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class PreviewActvity extends BaseActivity<ActivityPreviewBinding, BaseViewModel> {

    private TXVodPlayer mTXVodPlayer;
    private TXVodPlayConfig mTXPlayConfig;
    private TXCloudVideoView mTXCloudVideoView;
    private String mVideoPath;
    private ImageView mImageViewBg;
    private TXUGCPublish mVideoPublish;
    private String coverPath;
    private VideoWorkProgressFragment mWorkLoadingProgress;

    @Override
    public int initContentView() {
        return R.layout.activity_preview;
    }

    @Override
    public int initVariableId() {
        return BR.entity;
    }

    @Override
    public BaseViewModel initViewModel() {
        return new BaseViewModel(this);
    }

    @Override
    public void initData() {
        super.initData();

        Intent intent = getIntent();
        mVideoPath = intent.getStringExtra(TCConstants.VIDEO_RECORD_VIDEPATH);
        coverPath = intent.getStringExtra(TCConstants.VIDEO_RECORD_COVERPATH);

        mImageViewBg = findViewById(R.id.cover);
        Glide.with(this).load(Uri.fromFile(new File(coverPath))).into(mImageViewBg);


        mTXVodPlayer = new TXVodPlayer(this);
        mTXPlayConfig = new TXVodPlayConfig();

        mTXCloudVideoView = (TXCloudVideoView) findViewById(R.id.video_view);
        mTXCloudVideoView.disableLog(true);
        initPublish();
        startPlay();

        findViewById(R.id.publish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publish();
            }
        });
    }

    private void publish() {

        RetrofitClient.getInstance().create(SignatureService.class).getSignature("描述秒谁")
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showPeogress();
                    }
                })
                .subscribe(new Consumer<BaseResponse<String>>() {
                    @Override
                    public void accept(BaseResponse<String> response) throws Exception {
                        if (response.getCode() == 0) {
                            KLog.e(response.getData() + "=Signature");
                            // 文件发布默认是采用断点续传
                            TXUGCPublishTypeDef.TXPublishParam param = new TXUGCPublishTypeDef.TXPublishParam();
                            param.signature = response.getData();

                            // 需要填写第四步中计算的上传签名
                            // 录制生成的视频文件路径, ITXVideoRecordListener 的 onRecordComplete 回调中可以获取
                            param.videoPath = mVideoPath;
                            // 录制生成的视频首帧预览图，ITXVideoRecordListener 的 onRecordComplete 回调中可以获取
                            param.coverPath = coverPath;
                            mVideoPublish.publishVideo(param);

                        } else {
                            hideProgress();
                            ToastUtils.showShort("获取签名失败");
                        }
                    }
                }, new Consumer<ResponseThrowable>() {
                    @Override
                    public void accept(ResponseThrowable throwable) throws Exception {
                        hideProgress();
                    }
                });

    }


    private void initPublish() {
        mVideoPublish = new TXUGCPublish(this.getApplicationContext(), "independence_android");
        mVideoPublish.setListener(new TXUGCPublishTypeDef.ITXVideoPublishListener() {
            @Override
            public void onPublishProgress(long uploadBytes, long totalBytes) {
                if (mWorkLoadingProgress != null) {
                    mWorkLoadingProgress.setProgress((int) (100 * uploadBytes / totalBytes));
                }
            }

            @Override
            public void onPublishComplete(TXUGCPublishTypeDef.TXPublishResult result) {
                mWorkLoadingProgress.setProgress(100);
                mWorkLoadingProgress.dismiss();
                KLog.e("code=" + result.retCode + ",msg=" + result.descMsg + ",putl=" + result.coverURL + ",Vurl=" + result.videoURL);
                if (result.retCode == 0) {
                    ToastUtils.showShort("成功");
                } else {
                    ToastUtils.showShort(result.descMsg);
                }

            }
        });
    }

    private void stopPublish() {
        mVideoPublish.canclePublish();
    }

    private void hideProgress() {
        if (mWorkLoadingProgress != null) {
            mWorkLoadingProgress.setProgress(0);
            mWorkLoadingProgress.dismiss();
        }
    }

    private void startPlay() {
        mTXVodPlayer.setPlayerView(mTXCloudVideoView);
        mTXVodPlayer.enableHardwareDecode(false);
        mTXVodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
        mTXVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN);
        mTXVodPlayer.setConfig(mTXPlayConfig);
        //mTXVodPlayer.setVodListener(this);
        mTXVodPlayer.setLoop(true);
        mTXVodPlayer.startPlay(mVideoPath);
        mImageViewBg.setVisibility(View.GONE);
    }

    private void stopPlay(boolean clearLastFrame) {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.setVodListener(null);
            mTXVodPlayer.stopPlay(clearLastFrame);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mTXVodPlayer.isPlaying()) {
            mTXVodPlayer.resume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mTXCloudVideoView.onPause();

        mTXVodPlayer.pause();

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTXCloudVideoView.onDestroy();
        stopPlay(true);
        mTXVodPlayer = null;
        mTXPlayConfig = null;
        mTXCloudVideoView = null;

    }

    /**
     * ==========================================进度条==========================================
     */
    private void initWorkLoadingProgress() {
        if (mWorkLoadingProgress == null) {
            mWorkLoadingProgress = new VideoWorkProgressFragment();
            Bundle bundle = new Bundle();
            bundle.putString(VideoWorkProgressFragment.KEY_TITLE, "视频上传中");
            mWorkLoadingProgress.setArguments(bundle);
        }
        mWorkLoadingProgress.setProgress(0);
    }

    private void showPeogress() {

        if (mWorkLoadingProgress == null) {
            initWorkLoadingProgress();
        }
        mWorkLoadingProgress.setProgress(0);
        mWorkLoadingProgress.setCancelable(false);
        mWorkLoadingProgress.show(getSupportFragmentManager(), "progress_dialog");
    }


}
